<template>
	<view>
		<view class="content">
			<u-navbar :fixed="false" title="新建实验室任务" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff">
			</u-navbar>
			<scroll-view class="content_main scroll-Y" show-scrollbar :scroll-top="0" scroll-y="true">
				<u--form labelPosition="left" :model="formData" :rules="rules" ref="cTaskForm" labelWidth="100"
					:labelStyle="{fontSize:'14px',fontWeight:600}"
					style="padding: 0 10rpx 30rpx 30rpx;background-color: #fff;">
					<u-form-item label="产品名称" prop="ProductName" required rightIcon="arrow-right"
						@click="openBaseScreen('产品','radio')">
						<u--input v-model="formData.ProductName" readonly placeholder="请选择" border="none"></u--input>

						<view slot="right" class="x-f">
							<u-icon name="arrow-right" color="#999"></u-icon>
						</view>
					</u-form-item>
					<view class="f-dc" v-if="formData.ProductID"
						style="background-color: #f4f5fa;font-size: 12px;padding: 10rpx;color: #6f6f6f;font-weight: 600;border-radius: 5px;">
						<text>产品编号：{{formData.ProductCode}}</text>
						<text style="margin-top: 10rpx;">产品规格：{{formData.ProductSpec}}</text>
					</view>

					<u-form-item label="检测方案" prop="BillNO" required rightIcon="arrow-right">
						<u--input v-model="formData.BillNO" readonly placeholder="请选择产品" border="none"></u--input>
					</u-form-item>

					<u-form-item label="接收质量限" prop="AQL" required rightIcon="arrow-right">
						<u--input v-model="formData.AQL" readonly placeholder="请选择产品" border="none"></u--input>
					</u-form-item>

					<u-form-item label="送检数量" prop="BJNum" required rightIcon="arrow-right">
						<u--input v-model="formData.BJNum" :readonly="$m.utils.isEmpty(formData.LabTestPlanID)"
							:placeholder="$m.utils.isEmpty(formData.LabTestPlanID) ? '请确认检验方案' : '请输入送检数量'"
							type="number" border="none" @blur="getCJNumByBJNum"></u--input>
						<view slot="right" class="x-f">
							<u-icon name="edit-pen-fill" color="#999"></u-icon>
						</view>
					</u-form-item>
					<view class="f-dc" v-if="formData.CJNum"
						style="background-color: #f4f5fa;font-size: 12px;padding: 10rpx;color: #6f6f6f;font-weight: 600;border-radius: 5px;">
						<text>抽样数量：{{formData.CJNum}}</text>
					</view>

					<u-form-item label="负责人" prop="CuratorName" required rightIcon="arrow-right"
						@click="openBaseScreen('负责人','radio')">
						<u--input v-model="formData.CuratorName" readonly placeholder="请选择" border="none"></u--input>

						<view slot="right" class="x-f">
							<u-icon name="arrow-right" color="#999"></u-icon>
						</view>
					</u-form-item>

					<u-form-item label="预计结束时间" prop="TestEndTime" required rightIcon="arrow-right"
						@click="openBaseScreen('预计结束时间','time')">
						<u--input v-model="formData.TestEndTime" readonly placeholder="请选择" border="none"></u--input>

						<view slot="right" class="x-f">
							<u-icon name="calendar-fill" color="#999"></u-icon>
						</view>
					</u-form-item>
				</u--form>
			</scroll-view>

			<view class="content_bottom x-ec" style="background-color: #fff;">
				<button class="CommonBtnSize content_bottom_primary_Btn" style="margin-left: 10px;"
					@click="insetRow">提交</button>
			</view>
		</view>


		<!-- 时间选择器 -->
		<u-datetime-picker :show="showDateTimePicker" v-model="defaultData.choiceTime" mode="date" closeOnClickOverlay
			@confirm="timeChange" @cancel="cancelTimePicker" @close="cancelTimePicker"
			:formatter="formatter"></u-datetime-picker>
	</view>
</template>

<script>
	import {
		layer
	} from '../../common/comFun/utils';

	export default {
		data() {
			return {
				formData: {
					// 产品
					ProductCode: null,
					ProductName: null,
					ProductSpec: null,
					ProductInfo: null,
					ProductID: null,

					// 检测方案
					LabTestPlanID: null,
					BillNO: null,
					SamplingSchemeID: null,
					// 接收质量限
					AQL: null,
					// 送检数量
					BJNum: null,
					// 负责人
					Curator: null,
					CuratorName: null,
					// 截止日期
					TestEndTime: null

				},
				rules: {
					'ProductName': {
						type: 'string',
						required: true,
						message: '请选择产品',
						trigger: ['change']
					},
					'BillNO': {
						type: 'string',
						required: true,
						message: '未查询到检测方案',
						trigger: ['change']
					},
					'AQL': {
						type: 'string',
						required: true,
						message: '未查询到接收质量限',
						trigger: ['change']
					},
					'BJNum': {
						type: 'number',
						required: true,
						message: '请输入送检数量',
						trigger: ['blur']
					},
					'CuratorName': {
						type: 'string',
						required: true,
						message: '请选择负责人',
						trigger: ['change']
					},
					'TestEndTime': {
						type: 'string',
						required: true,
						message: '请选择预计结束时间',
						trigger: ['change']
					},
				},
				showDateTimePicker: false,
				defaultData: {
					choiceTime: null,
				},
			};
		},
		mounted() {
			let that = this;

			uni.$on("selectCreatTask_product", function(ret) {
				console.log(ret);
				switch (ret.type) {
					case "产品":
						Object.assign(that.formData, ret.data);

						that.$refs.cTaskForm.validateField('ProductName');
						// 根据产品信息获取检测方案
						that.getLabReportPlanByProduct();
						break;
					case "负责人":
						let data = {
							Curator: ret.data["EmplID"],
							CuratorName: ret.data["EmplCode"] + "_" + ret.data["EmplName"],
						}
						Object.assign(that.formData, data);
						that.$refs.cTaskForm.validateField('CuratorName');
						break;
					default:
						break;
				}
			});
		},
		onUnload() {
			let that = this;
			uni.$off("selectCreatTask_product");
		},
		methods: {
			formatter(type, value) { // u-datetime-picker 时间映射
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			timeChange(data) { // 时间选择--点击确认
				let that = this;

				that.$set(that.formData, "TestEndTime", that.$utils.dateFormat(new Date(data.value), 'Y-MM-dd'));

				that.$refs.cTaskForm.validateField('TestEndTime');
				that.showDateTimePicker = false;
			},
			cancelTimePicker() {
				this.showDateTimePicker = false;
			},
			/**
			 * 根据产品信息获取检测方案
			 */
			getLabReportPlanByProduct() {
				let that = this;

				this.$utils.clearFormData(this.formData, ["ProductID", "ProductName", "ProductCode", "ProductInfo",
					"ProductSpec", "Curator", "CuratorName", "TestEndTime"
				])

				if (this.$utils.isEmpty(this.formData.ProductID)) {
					return this.$utils.layer.alert("当前物料信息加载异常，请重新选择物料！")
				};

				this.$request("Qu_LabTestSelectPlanByProduct", {
					ProductID: this.formData.ProductID
				}, function(ret) {
					console.log(ret);
					if (ret.status == 200) {
						let data = {
							LabTestPlanID: null,
							BillNO: null,
							SamplingSchemeID: null,
							AQL: null,
						};

						if (ret.data.ds.length) {
							Object.assign(data, ret.data.ds[0]);
						};
						Object.assign(that.formData, data);

						that.$refs.cTaskForm.validateField('BillNO');
						// that.$refs.cTaskForm.validateField('LabTestPlanID');
						that.$refs.cTaskForm.validateField('SamplingSchemeID');
						that.$refs.cTaskForm.validateField('AQL');
					}
				}, function(err) {

				})
			},
			/**
			 * 根据送检数量获取抽样数量
			 */
			getCJNumByBJNum(val) {
				let that = this;
				if (this.$utils.isEmpty(val)) {
					let obj = {
						BJNum: null,
						CJNum: null,
					};
					Object.assign(this.formData, obj);
					return;
				};

				that.$refs.cTaskForm.validateField('BJNum');

				that.$request("Qu_LabTestGetCjNum", {
					BJNum: val,
					SamplingSchemeID: that.formData.SamplingSchemeID
				}, function(ret) {
					console.log(ret);
					if (ret.status == 200) {
						that.$set(that.formData, "CJNum", ret.data.ds[0]['CJNum']);
					}
				}, function(err) {
					console.log(err);
				})
			},
			openBaseScreen(str, type) {
				let that = this;
				let obj = {};
				let url = "";
				switch (type) {
					case "radio":

						url = '/commonPage/Tool/baseScreen';

						switch (str) {
							case "产品":
								obj = {
									allowClear: false,
									cmd: 'XGD_Material',
									type: str,
									ListeningName: 'selectCreatTask_product',
									// multiple: false,
									serverSearch: {
										isPaging: true, //是否分页
										searchKey: 'SearchKey', //搜索关键词，应包含在param中
										showText: 'ProductInfo', //查询结果显示的字段
										pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
										ChoiceDataKey: 'ProductID',
										ChoiceDataData: this.formData.ProductID,
									},
									param: {
										SearchKey: '',
										PageIndex: 1,
										PageSize: 30
									}
								}

								break;
							case "负责人":
								obj = {
									allowClear: false,
									cmd: 'XGD_Employee',
									type: str,
									ListeningName: 'selectCreatTask_product',
									// multiple: false,
									serverSearch: {
										isPaging: true, //是否分页
										searchKey: 'EmplCode', //搜索关键词，应包含在param中
										showText: 'EmplName', //查询结果显示的字段
										pageIndexStr: 'Pageindex', //分页页码字段，应包含在param中
										subText: [{
											label: '编号',
											labelKey: 'EmplCode'
										}],
										ChoiceDataKey: 'EmplID',
										ChoiceDataData: this.formData.Curator,
									},
									param: {
										EmplCode: '',
										Pageindex: 1,
										PageSize: 30
									}
								}

								break;

							default:
								break;
						}


						that.$store.commit('ChangeAndSetStateData', {
							Name1: 'BaseScreenParm',
							data: obj
						});

						uni.navigateTo({
							url: url
						})

						break;
					case "check":

						break;
					case "time":
						switch (str) {
							case "预计结束时间":
								let nowTime = new Date();
								if (!that.$utils.isEmpty(that.formData.TestEndTime)) {
									nowTime = new Date(that.formData.TestEndTime);
								};
								that.$set(that.defaultData, "choiceTime", +nowTime);
								that.showDateTimePicker = true;
								break;
							default:
								break;
						}
						break;
					default:
						break;
				}
			},
			insetRow() { // 提交
				let that = this;

				this.$utils.showLoading("正在校验...");

				this.$refs.cTaskForm.validate().then(res => {

					that.$utils.showLoading("校验成功，准备提交");

					let param = {
						ProductID: this.formData.ProductID,
						Curator: this.formData.Curator,
						SamplingSchemeID: this.formData.SamplingSchemeID,
						BJNum: this.formData.BJNum,
						UserName: this.$store.state.UserInfo.UserName,
						LabTestPlanID: this.formData.LabTestPlanID,
						TestEndTime: this.formData.TestEndTime,
					};
					console.log(param);

					that.$request("Qu_LabTestCreateBillNO", param, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							if (ret.data.ds[0]['status'] == 200) {
								// 画一个弹层，用于提示成功，并确认退出或继续编辑
								that.$utils.hideLoading();
								uni.showToast({
									title: "提交成功！"
								});
								uni.$emit("refreshToLabReport_list");
								uni.navigateBack();
							}
						}
					}, function(err) {
						console.log(err);
						that.$utils.hideLoading();
					})
				}).catch(errors => {
					console.log(errors);
					that.$utils.hideLoading();
					uni.$u.toast('请完善表单信息');
				})

			},
		}
	}
</script>

<style lang="scss">
	.content {
		// background-color: #fff;

		&_main {}
	}
</style>